<?php

namespace app\health\controller;

use app\health\model\HealthGoods;
use app\health\model\HealthGoodsAccess;
use app\health\model\HealthWebsiteBanner;

class Goods extends ApiBase
{
    protected $noNeedLogin = ['lists', 'detail', 'banner'];

    /**
     * 商品列表页轮播图
     * @Author 张旭鹏
     * @DateTime 2023-07-19
     */
    public function banner()
    {
        $banner = HealthWebsiteBanner::where('position', 2)->where('status', 1)->field('id,name,image,type,params,status')->select();
        $this->success('', $banner);
    }

    /**
     * 商品列表
     * @Author 张旭鹏
     * @DateTime 2023-06-13
     */
    public function lists()
    {
        $limit      = $this->request->param('limit/d', 10);
        $goods_name = $this->request->param('goods_name', '');
        $where      = ['is_enable' => ['=', 1], 'is_del' => ['=', 1]];
        if ($goods_name) {
            $where['goods_name'] = ['like', "%{$goods_name}%"];
        }
        $paginate = HealthGoods::where($where)
            ->field('id,goods_name as name,mix_title as introduce,image,price,lineation_price as market_price,sales_total,virtually_sales_total,is_enable,tag')
            ->order('sort', 'desc')
            ->paginate($limit)
            ->each(function ($item) {
                $item->append(['total_sales', 'tag_text']);
                $item->hidden(['sales_total', 'virtually_sales_total', 'is_enable']);
            });
        $this->success('', $paginate);
    }

    /**
     * 商品详情
     * @Author 张旭鹏
     * @DateTime 2023-07-03
     */
    public function detail()
    {
        $params = $this->request->post();
        if (!isset($params['goods_id']) || empty($params['goods_id'])) {
            $this->error('请选择商品');
        }
        $where = ['is_del' => ['=', 1], 'id' => $params['goods_id']];
        $goods = HealthGoods::where($where)
            ->field('id,goods_name,is_enable,carousel_image,state,price,guarantee,introduction,add_time,lineation_price,mix_title,virtually_sales_total,sales_total')
            ->find();
        if (!$goods) {
            $this->error('商品不存在');
        }
        if (empty($goods->is_enable)) {
            $this->error('商品已下架');
        }
        $carousel_image = explode(',', $goods->carousel_image);
        foreach ($carousel_image as &$i) {
            $i = cdnurl($i, true);
        }
        $goods->carousel_image = $carousel_image;
        $goods->goodsAttr;
        $goods->append(['total_sales']);
        $goods->hidden(['virtually_sales_total', 'sales_total']);
        //记录商品访问记录
        HealthGoodsAccess::create([
            'goods_id' => $params['goods_id'],
            'user_id'  => $this->auth->id ?? 0,
            'ip'       => $this->request->ip(),
        ]);
        $this->success('', $goods);
    }
}
